package org.amos.tenant.core;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import org.amos.core.basic.context.TenantContextHolder;
import org.amos.tenant.properties.TenantProperties;

import java.util.HashSet;
import java.util.Set;

/**
 * 自定义多租户处理插件
 */
public class CustomTenantLineHandler implements TenantLineHandler {

    private final Set<String> EXCLUDE_TABLES = new HashSet<>();

    public CustomTenantLineHandler(TenantProperties properties) {
        Assert.state(CollUtil.isNotEmpty(properties.getExcludeTables()), "excludeTables is empty");
        EXCLUDE_TABLES.addAll(properties.getExcludeTables());
    }

    @Override
    public Expression getTenantId() {
        return new LongValue(TenantContextHolder.getRequiredTenantId());
    }

    @Override
    public boolean ignoreTable(String tableName) {
        return TenantContextHolder.isIgnore() || CollUtil.contains(EXCLUDE_TABLES, tableName);
    }

}
